import socket
import re
import multiprocessing
import dynamic.my_web_decorator


class WSGIServer(object):
    def __init__(self):
        # 1.create a socket
        self.tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)

        # 2.bind the address
        self.tcp_server_socket.bind(('',7788))

        # 3.create a listen socket
        self.tcp_server_socket.listen(128)

    def run_forever(self):
        while True:
            new_socket, client_addr = self.tcp_server_socket.accept()
            p = multiprocessing.Process(target=self.service_client,args=(new_socket,))
            p.start()
            new_socket.close()

    def service_client(self, new_socket):
        # # GET / HTTP/1.1
        request = new_socket.recv(1024).decode("utf-8")
        request_lines = request.splitlines()
        print("")
        print('>'*20)
        print(request_lines)

        file_name = ''
        ret = re.match(r"[^/]+(/[^ ]*)",request_lines[0])
        if ret:
            file_name = ret.group(1)
            if file_name == '/':
                file_name = '/index.html'

        if not file_name.endswith('.html'):
            try:
                f = open('./static' + file_name, 'rb')
            except:
                response = "HTTP/1.1 404 NOT FOUND\r\n"
                response += "\r\n"
                response += "------file not found-----"
                new_socket.send(response.encode("utf-8"))
            else:
                html_content = f.read()
                f.close()
                response = "HTTP/1.1 200 OK\r\n"
                response += "\r\n"
                new_socket.send(response.encode("utf-8"))
                new_socket.send(html_content)
        else:
            env = dict()
            env['PATH_INFO'] = file_name
            body = dynamic.my_web_decorator.application(env, self.star_response)
            header = "HTTP/1.1 %s\r\n"%self.status
            for temp in self.header:
                header += '%s:%s\r\n'%(temp[0],temp[1])
            header += '\r\n'
            response = header+body
            new_socket.send(response.encode('utf-8'))
        new_socket.close()

    def star_response(self, status, header):
        self.status = status
        self.header = header


def main():
    wsgi_server = WSGIServer()
    wsgi_server.run_forever()

if __name__ == "__main__":
    main()
